package models.permission;

import models.common.CodeStatus;
import play.db.jpa.Model;
import utils.ShouldSkip;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Entity
@Table(name="tt_ADMIN_PERMISSION_ROLE")
public class Role extends Model implements models.deadbolt.Role{

	/**
	 * 角色名称
	 */
	public String name;

	/**
	 * 角色代码
	 */
	public String code;
	/**
	 * 角色简介
	 */
	public String remark;

	/**
	 * 状态
	 */
	@Enumerated(EnumType.STRING)
	public CodeStatus status;

	@OneToMany(mappedBy = "role")
	@ShouldSkip
	public Set<User> users = new HashSet<User>();
	
	@ManyToMany(cascade = CascadeType.ALL)
	@JoinTable(name="tt_Admin_RoleMenu",joinColumns=@JoinColumn(name="role_code",referencedColumnName="code"),
			inverseJoinColumns=@JoinColumn(name="menu_code",referencedColumnName="code"))
	public List<Menu> menus = new ArrayList<Menu>();

	public List<String> resourcePerms() {
		List<String> resourceNames = new ArrayList();
		for(Menu menu: menus) {
			resourceNames.add(menu.perms);
		}
		return resourceNames;
	}

	@Override
	public String getRoleName() {
		return name; 
	} 
	
	public boolean hasResource(String perms) {
		Menu res = models.permission.Menu.getResourceByPerms(perms);
		if(menus.contains(res)) {
			return true; 
		}
		return false; 
	}
	
	public boolean hasResources(List<String> res) { 
		List<String> resourceNames = resourcePerms();
		resourceNames.retainAll(res);
		if(resourceNames.size() > 0) { 
			return true; 
		}
		return false; 
	}
}
